/** Mode handler for the help library.
 *@param buffer The buffer to render to.
 */
function HelpLibraryMode(buffer)
{
	this.buffer = buffer;
	this.libraryStack = [];
	this.libraryStack.push(docs);
	this._doLibraryStack();
}
HelpLibraryMode.prototype =
{
	/** Handle whatever is at the end of the library stack.
	 */
	_doLibraryStack: function()
	{
		// Nothing left, exit
		if(this.libraryStack.length <= 0)
		{
			dhack.removeModeHandler(this);
			return;
		}

		var lib = this.libraryStack[this.libraryStack.length - 1];
		
		// We are processing a topic, display the text for it.
		if(typeof(lib) === "string")
		{
			dhack.addModeHandler(
				new TextReaderMode(
					this.buffer,
					text[lib],
					this._textReaderCallback,
					this
				)
			);
			return;
		}

		// We are processing a document library.
		var options = ["%90Back%f0"];
		for(var i = 0; i < lib.docs.length; ++i)
		{
			var item = lib.docs[i];
			if(typeof(item) === "string")
				options.push(item);
			else
				options.push(item.title);
		}
		dhack.addModeHandler(
			new MenuListMode(
				this.buffer,
				40,
				"%e0" + lib.title + "%f0",
				options,
				this._documentLibraryCallback,
				this,
				false,
				false,
				true
			)
		);
	},
	/** Callback handler for a document library's MenuListMode.
	 *@param option The option selected.
	 *@param source The MenuListMode object that called the callback.
	 */
	_documentLibraryCallback: function(option, source)
	{
		// Canceled
		if(option === null ||
			option == "%90Back%f0")
		{
			this.libraryStack.pop();
			this._doLibraryStack();
			return;
		}

		// Find what item was selected and process it
		var lib = this.libraryStack[this.libraryStack.length - 1];
		for(var i = 0; i < lib.docs.length; ++i)
		{
			var item = lib.docs[i];
			if(
				(typeof(item) === "string" &&
					item === option) ||
				(typeof(item) === "object" &&
					item.title === option)
			)
			{
				this.libraryStack.push(item);
				this._doLibraryStack();
				return;
			}
		}

		// We should never get here...
		throw "_documentLibraryCallback() failed to locate document item requested.";
	},
	/** Callback handler for a topic's TextReaderMode.
	 */
	_textReaderCallback: function()
	{
		this.libraryStack.pop();
		this._doLibraryStack();
	}
};
